<template>
    <div>
        <!-- 此处注意写法v-model:content -->
      <QuillEditor ref="myQuillEditor"
        theme="snow"
        v-model:content="content"
        :options="state.editorOption"
        contentType="html"
        @update:content="setValue()"
      />
      <!-- 使用自定义图片上传 -->
      <input type="file" hidden accept=".jpg,.png" ref="fileBtn" @change="handleUpload" />
    </div>
  </template>
  
  <script lang="ts" setup>
  import { QuillEditor } from '@vueup/vue-quill'
  import '@vueup/vue-quill/dist/vue-quill.snow.css'
  import { reactive, onMounted, ref, toRaw, watch } from 'vue'
  
  const props = defineProps(['value'])
  const emit = defineEmits(['update:value'])
  const content = ref('')
  const myQuillEditor = ref()
  const url= import.meta.env.VITE_APP_UPLOAD_URL+"/uploads"
  const imageUrl =import.meta.env.VITE_APP_IMAGE_URL;
  // 通过watch监听回显，笔者这边使用v-model:content 不能正常回显
  watch(() => props.value, (val) => {
    if(val && myQuillEditor.value){
      toRaw(myQuillEditor.value).setHTML(val)
    }
  }, { deep: true,immediate:true })
  const fileBtn = ref()
  const state = reactive({
    content: '',
    editorOption: {
      modules: {
        toolbar: [
          ['bold', 'italic', 'underline', 'strike'],
          [{ 'size': ['small', false, 'large', 'huge'] }],
          [{ 'font': [] }],
          [{ 'align': [] }],
          [{ 'list': 'ordered' }, { 'list': 'bullet' }],
          [{ 'indent': '-1' }, { 'indent': '+1' }],
          [{ 'header': 1 }, { 'header': 2 }],
          ['image'],
          [{ 'direction': 'rtl' }],
          [{ 'color': [] }, { 'background': [] }]
        ]
      },
      placeholder: '请输入内容...'
    }
  })
  const imgHandler = (state:any) => {
    if (state) {
      fileBtn.value.click()
    }
  }
  // 抛出更改内容，此处避免出错直接使用文档提供的getHTML方法
  const setValue = () => {
    const text:string = toRaw(myQuillEditor.value).getHTML()
    emit("update:value",text)
  }
  const handleUpload = (e:any) => {
    const files = Array.prototype.slice.call(e.target.files)
    console.log(files, "files")
    if (!files) {
      return
    }
    const formdata = new FormData()
    formdata.append('file', files[0])
    console.log("file--->",files[0])
    doUpload(formdata);  // 此处使用服务端提供上传接口
  }

  /**
 * 发送上传请求
 * @param file
 * @param sign
 * @private
 */
const doUpload = (file: any) => {
  const uploadForm = new FormData();
  uploadForm.append('file', file);
  const xhr = new XMLHttpRequest();
  // 上传进度监听
  xhr.upload.onprogress = function (e) {
    if (e.type == 'progress') {
      const percent = Math.round((e.loaded / e.total) * 100);
    }
  };

  // 上传结果
  xhr.onreadystatechange = function (e) {
    if (xhr.readyState == 4) {
      if (xhr.status == 200 || xhr.status == 201 || xhr.status == 204) {
        console.log("res--->",xhr)
        if (xhr.response) {
          let data =JSON.parse(xhr.response);
          const quill = toRaw(myQuillEditor.value).getQuill()
          const length = quill.getSelection().index
          quill.insertEmbed(length, 'image', imageUrl+data.key)
          quill.setSelection(length + 1)
        }
        console.log(
          `%c OSS %c 上传成功 %c`,
          'background:#35495e ; padding: 1px; border-radius: 3px 0 0 3px;  color: #fff',
          'background:#41b883 ; padding: 1px; border-radius: 0 3px 3px 0;  color: #fff',
          'background:transparent',
        );
      } else {
      }
    }
  };

  xhr.open('POST', url);
  xhr.send(file);
};
  // 初始化编辑器
  onMounted(() => {
    const quill = toRaw(myQuillEditor.value).getQuill()
    if (myQuillEditor.value) {
      quill.getModule('toolbar').addHandler('image', imgHandler)
    }
    if(props.value && myQuillEditor.value){
      toRaw(myQuillEditor.value).setHTML(props.value)
    }
  })
  </script>
  <style scoped lang="less">
  // 调整样式
  :deep(.ql-editor) {
    min-height: 180px;
  }
  :deep(.ql-formats) {
    height: 21px;
    line-height: 21px;
  }
  </style>
  
  